/**
 * Created by pujingliang on 16/11/2.
 */

(function($) {

    //获取页面间的url的参数
    (function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);

    var teamName = '';
    var type = $.getUrlParam('type');          //页面类型 1新建项目
    var project_id = $.getUrlParam('project_id');
    var project = "";
    var members_arr = [];
    var members_name_arr = [];
    var members_avatar_arr = [];
    var members_qyxBindId_arr=[];

    var contact_arr         = [];
    var contact_name_arr    = [];
    var contact_avatar_arr  = [];
    var contact_qyxBindId_arr=[];

    $(function () {
        configView();
    });

    function configView() {
        $(".call_back").hide();

        //限制字数
        $(".projectName").bind("input propertychange",function(){
            var nameStr = $(this).val();
            if(nameStr.length >= 40){
                $(".project-alert").text("项目名最多40字").show().fadeOut(2000);
            }
        });

        //添加成员方法
        $("#addMember").click(
            function(){
                contact_arr = [];
                contact_avatar_arr = [];
                contact_name_arr = [];
                contact_qyxBindId_arr = [];
                for (var i=0;i<members_arr.length;i++){
                    contact_arr.push(members_arr[i]);
                }
                for (var i=0;i<members_avatar_arr.length;i++){
                    contact_avatar_arr.push(members_avatar_arr[i]);
                }
                for (var i=0;i<members_name_arr.length;i++){
                    contact_name_arr.push(members_name_arr[i]);
                }
                for (var i=0;i<members_qyxBindId_arr.length;i++){
                    contact_qyxBindId_arr.push(members_qyxBindId_arr[i]);
                }
                $("#addMemberDiv").show();
                $("#projectDiv").hide();
                getTeamName();
            }
        );

        $("#addMemberNavigation-right").click(
            function (){
                $(".newProject-li-image").remove();
                $("#addMemberDiv").hide();
                $("#projectDiv").show();
                $(".team_bigest").remove();
                $(".user_mid").remove();
                $(".com_line").remove();
                members_arr = [];
                members_avatar_arr = [];
                members_name_arr = [];
                members_qyxBindId_arr = [];
                for (var i=0;i<contact_arr.length;i++){
                    members_arr.push(contact_arr[i]);
                }
                for (var i=0;i<contact_qyxBindId_arr.length;i++){
                    members_qyxBindId_arr.push(contact_qyxBindId_arr[i]);
                }
                for (var i=0;i<contact_name_arr.length;i++){
                    members_name_arr.push(contact_name_arr[i]);
                }
                for (var i=0;i<contact_avatar_arr.length;i++){
                    members_avatar_arr.push(contact_avatar_arr[i]);
                    var img_url;
                    //if (contact_avatar_arr[i] == "") {
                        var color = avatar_getColor(members_qyxBindId_arr[i]);
                        img_url = "<div class='user_pic_div' style='background-color: " + color + "'>" + avatar_name(contact_name_arr[i]) + "</div>"
                    //} else {
                    if (contact_avatar_arr[i].length > 0) {
                        var src = avatar_getUrl(localStorage.user_id, localStorage.token, contact_avatar_arr[i]);
                        img_url += "<img src='" + src + "' class='user_pic' hidden>";
                    }
                    var html = '<li class="newProject-li-image" userId="'+contact_arr[i]+'">'+
                        img_url+
                        '</li>';
                    $(".project-ul").append(html);
                }

                showAvatar(".user_pic");
            }
        );

        //返回按钮方法
        $("#addMemberNavigation-left").click(
            function (){
                contact_arr = [];
                contact_avatar_arr = [];
                contact_name_arr = [];
                contact_qyxBindId_arr=[];
                $("#addMemberDiv").hide();
                $("#projectDiv").show();
                $(".team_bigest").remove();
                $(".user_mid").remove();
                $(".com_line").remove();
            }
        );

        //取消Alert
        $("#cancel").click(
            function (){
                $(".call_back").hide();
            }
        );
        //确认删除
        $("#sure").click(
            function (){
                if(user_id == project.user_id){
                    deteleProject(project_id);
                }
                else {
                    $(".project-alert").text("您无权限删除项目").show().fadeOut(2000);
                }
            }
        );

        if (type=='createNew') {
            myselfUserInfo();
            $("#deleteContainer").hide();
            $(".title").text("新建项目");
            $("#saveProject").click(
                function (){
                    //创建项目
                    var projectVal = HTMLEncode($(".projectName").val());
                    var projectTitle = $.trim(projectVal);

                    //var projectTitle = $(".projectName").html();
                    if ( projectTitle == ""){
                        $(".project-alert").text("项目标题不能为空").show().fadeOut(2000);
                    }else {
                        createProject(user_id,group_id,projectTitle);
                    }
                }
            );
            //返回按钮方法
            $("#newProjectBack").click(
                function (){
                    window.location.href="../../index.html?htmlType=1";
                }
            );
        }
        else {
            $("#deleteContainer").show();
            $(".title").text("设置项目");
            projectDetail(project_id);
            //返回按钮方法
            $("#newProjectBack").click(
                function (){
                    window.location.href="projectDetail.html?project_id="+project_id+"&tabbarCount=1";
                }
            );

            $("#saveProject").click(
                function (){
                    //修改项目
                    var projectVal = HTMLEncode($(".projectName").val());
                    var projectTitle = $.trim(projectVal);

                    //var projectTitle = $(".projectName").html();
                    if ( projectTitle == ""){
                        $(".project-alert").text("项目标题不能为空").show().fadeOut(2000);
                    }else {
                        if(user_id == project.user_id){
                            changeProject(project_id,projectTitle);
                        }
                        else {
                            $(".project-alert").text("您无权限修改项目").show().fadeOut(2000);
                        }

                    }
                }
            );

            $("#delete").click(
                function (){
                    //删除项目
                    $(".call_back").show();
                }
            );
        }

        $(document).on("click",".newProject-li-image",function(){
            var id = $(this).attr("userId");
            if (id == user_id){
                $(".project-alert").text("不能删除自己").show().fadeOut(2000);
            }
            else {
                for (var i=0;i<members_arr.length;i++){
                    if (id == members_arr[i]){
                        members_arr.splice(i,1);
                        members_avatar_arr.splice(i,1);
                        members_name_arr.splice(i,1);
                        members_qyxBindId_arr.splice(i,1);
                        $(this).remove();
                    }
                }
            }
        });
    }

    //获取团队名
    function getTeamName(){
        var url_c  = tk_apiurl+"contacteam/findone";
        var data = {"userId":user_id,"token":token,"data":JSON.stringify({'id':group_id})};
        $.ajax({
            beforeSend:function(){
                $(".loading").show();
            },
            async: false,
            crossDomain: true,
            url: url_c,
            method: "POST",
            data:data,
            jsonpCallback:"jsoncallback",
            dataType: "jsonp",
            success:function(d) {
                var data1 = '';
                var status = '';

                data = eval('(' + d + ')');
                status = data.statusCode;
                if (status == 200){
                    if (data.result) {
                        data1 = eval('(' + data.result + ')');
                    }

                    teamName = data1.teamName;
                    initpart();
                }
                else {
                    if (data.statusCode == 202 || data.statusCode == 203){
                        $(".token_iframe").show();
                    }
                    else {
                        $(".addMemberProject-alert").text(data.message).show().fadeOut(2000);
                    }
                }
            },
            error:function(){
                $(".addMemberProject-alert").text("网络不给力").show().fadeOut(2000);
            }
        });
    }

    //获取个人信息
    function myselfUserInfo() {
        var url    = tk_apiurl+"user/userinfo";
        var data   = {"userId":user_id,"token":token,"data":JSON.stringify({'userId':user_id})};
        $.ajax({
            beforeSend:function(){
                $(".newCreateLoading").show();
                $(".content-div").hide();
            },
            complete:function(){
                $(".newCreateLoading").hide();
            },
            async: true,
            crossDomain: true,
            url: url,
            method: "POST",
            data:data,
            jsonpCallback:"jsoncallback",
            dataType: "jsonp",
            success:function(d){
                var data='';
                var data1='';
                data = eval('('+d+')');
                if (data.statusCode == 200){
                    data1 = eval('('+data.result+')');
                    members_arr.push(data1.id);
                    members_avatar_arr.push(data1.avatar);
                    members_name_arr.push(data1.name);
                    members_qyxBindId_arr.push(data1.qyxBindId);
                    var img_url;
                    //if (data1.avatar == "") {
                        var color = avatar_getColor(data1.qyxBindId);
                        img_url = "<div class='user_pic_div' style='background-color: " + color + "'>" + avatar_name(data1.name) + "</div>"
                    //} else {
                    if (data1.avatar.length > 0) {
                        var src = avatar_getUrl(localStorage.user_id, localStorage.token, data1.avatar);
                        img_url += "<img src='" + src + "' class='user_pic' hidden>";
                    }
                    var html = '<li class="newProject-li"><p class="newProject-p">项目成员</p></li>'+
                        '<li class="newProject-li-image" userId="'+data1.id+'">'+
                        img_url+
                        '</li>';
                    $(".project-ul").append(html);
                    $(".content-div").show();
                }else {
                    if (data.statusCode == 202 || data.statusCode == 203){
                        $(".token_iframe").show();
                    }
                    else {
                        $(".project-alert").text(data.message).show().fadeOut(2000);
                    }
                }
                showAvatar(".user_pic");
            },
            error:function(){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        });
    }
    //获取项目详情
    function projectDetail(project_id) {
        var url = apiurl+"/projects/"+project_id+"";
        var urlData = {
            user_id:user_id,
            token:token
        }
        $.ajax({
            url:url,
            type:"GET",
            data:urlData,
            beforeSend:function(){
                $(".newCreateLoading").show();
                $(".content-div").hide();
            },
            complete:function(){
                $(".newCreateLoading").hide();
            },
            success:function(d){
                if (d.msg == 202){
                    $(".token_iframe").show();
                }
                else {
                    var comData = d;
                    if (d.code == undefined) {
                        comData = JSON.parse(d);
                    }
                    if (comData.code == 0) {
                        var data = JSON.parse(d).data;
                        project = data;
                        var title = data.project_title;
                        var newTitle = INPUTEncode(title);
                        $(".projectName").val(newTitle);
                        var html = '<li class="newProject-li"><p class="newProject-p">项目成员</p></li>';
                        var userArray = data.userCallbackString;
                        for (key in userArray) {
                            members_arr.push(userArray[key].id);
                            members_avatar_arr.push(userArray[key].avatar);
                            members_name_arr.push(userArray[key].name);
                            members_qyxBindId_arr.push(userArray[key].qyxBindId);
                            var img_url;
                            //if (userArray[key].avatar == "") {
                                var color = avatar_getColor(userArray[key].qyxBindId);
                                img_url = "<div class='user_pic_div' style='background-color: " + color + "'>" + avatar_name(userArray[key].name) + "</div>"
                            //} else {
                            if (userArray[key].avatar.length > 0) {
                                var src = avatar_getUrl(localStorage.user_id, localStorage.token, userArray[key].avatar);
                                img_url += "<img src='" + src + "' class='user_pic' hidden>";
                            }
                            html += '<li class="newProject-li-image" userId="' + userArray[key].id + '">' +
                                img_url +
                                '</li>';
                        }
                        $(".project-ul").append(html);
                        $(".content-div").show();

                        showAvatar(".user_pic");
                    }
                    else {
                        $(".project-alert").text("Error").show().fadeOut(2000);
                    }
                }
            },
            error:function(){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //创建项目
    function createProject(user_id,group_id,project_title) {
        //user_id 创建人id
        //group_id 项目群组id
        //project_title 项目名
        //members  项目成员id (多个用逗号隔开)
        var members = "";
        for (key in members_arr) {
            if (members.length == 0){
                members = members+members_arr[key];
            }
            else {
                members = members+","+members_arr[key];
            }
        }
        var url = apiurl+"/projects";
        var data = {
            user_id:user_id,
            group_id:group_id,
            project_title:project_title,
            members:members
        }
        $.ajax({
            url:url,
            type:"POST",
            data:data,
            beforeSend:function(){
                $(".change-p").text("正在创建项目");
                $(".change-alert").show();
            },
            complete: function () {
                $(".change-alert").hide();
            },
            success:function(d){
                var data = d;
                if (d.code == undefined) {
                    data = JSON.parse(d);
                }
                if (data.code == 0){
                    $(".project-alert").text("创建项目成功").show().fadeOut(2000);
                    window.location.href="../../index.html?htmlType=1";
                }
                else {
                    $(".project-alert").text("Error").show().fadeOut(2000);
                }
            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //修改项目
    function changeProject(project_id,project_title) {
        //project_id 项目id
        //project_title 项目名
        //members  项目成员id (多个用逗号隔开)
        var members = "";
        for (key in members_arr) {
            if (members.length == 0){
                members = members+members_arr[key];
            }
            else {
                members = members+","+members_arr[key];
            }
        }
        var url = apiurl+"/projects/"+project_id+"";
        var data = {
            project_title:project_title,
            members:members
        }
        $.ajax({
            url:url,
            type:"PUT",
            data:data,
            beforeSend:function(){
                $(".change-p").text("正在修改项目");
                $(".change-alert").show();
            },
            complete: function () {
                $(".change-alert").hide();
            },
            success:function(d){
                var data = d;
                if (d.code == undefined) {
                    data = JSON.parse(d);
                }
                if (data.code == 0){
                    $(".project-alert").text("项目修改成功").show().fadeOut(2000);
                    window.location.href="projectDetail.html?project_id="+project_id+"&tabbarCount=1";
                }
                else {
                    $(".project-alert").text("Error").show().fadeOut(2000);
                }
            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //删除项目
    function deteleProject(project_id) {
        //project_id 项目id
        var url = apiurl+"/projects/"+project_id+"";
        $.ajax({
            url:url,
            type:"DELETE",
            beforeSend:function(){
                $(".change-p").text("正在删除项目");
                $(".change-alert").show();
            },
            complete: function () {
                $(".change-alert").hide();
            },
            success:function(d){
                var data = d;
                if (d.code == undefined) {
                    data = JSON.parse(d);
                }
                if (data.code == 0){
                    $(".project-alert").text("删除项目成功").show().fadeOut(2000);
                    window.location.href="../../index.html?htmlType=1";
                }
                else {
                    $(".project-alert").text("Error").show().fadeOut(2000);
                }
            },
            error:function(d){
                $(".project-alert").text("网络不给力").show().fadeOut(2000);
            }
        })
    }

    //获取部门列表
    function initpart(){
        var url_c  = tk_apiurl+"contacteam/mydepts";
        var data = {"userId":user_id,"token":token,"data":JSON.stringify({'teamId':group_id,'parentId':"0"})};
        $.ajax({
            complete:function(){
                $(".loading").hide();
            },
            async: true,
            crossDomain: true,
            url: url_c,
            method: "POST",
            data:data,
            jsonpCallback:"jsoncallback",
            dataType: "jsonp",
            success:function(d){
                var data='';
                var data1='';
                data = eval('('+d+')');
                if (data.statusCode == 200){
                    data1 = eval('('+data.result+')');
                    var team = data1.depts;
                    var html = '';
                    $(".team_name_addMember").html(teamName);
                    $(".addMemberTitle").text(teamName);
                    for(var i=0;i<team.length;i++){
                        html +="<div class='team_bigest' id='"+team[i].id+"'>" +
                            "<div class='team_mid' is_choice='0'>" +
                            "<div class='team_left'>" +
                            "<div class='team_name'>"+team[i].departmentName+"</div>" +
                            "</div>" +
                            "<div class='team_right'>" +
                            "<img src='../../../log/logImg/rightIcon.png' class='right_icon'></div></div>" +
                            "<div class='contact_content'></div></div>";
                    }

                    html += "<div class='com_line'></div>";
                    var users = data1.users;
                    var html_users="";

                    for(var a=0;a<users.length;a++) {
                        var _choice = "0";
                        var _img = "<img src='../../images/task/circleCheckBoxUnselect.png' class='tick_icon'>";

                        for (var j = 0; j < contact_arr.length; j++) {
                            if (contact_arr[j] == users[a].userId) {
                                _choice = "1";
                                _img = "<img src='../../images/task/circleCheckBoxSelect.png' class='tick_icon'>";
                            }
                        }
                        var img_url;
                        var avatar1 = users[a].avatar;
                        var qyxBindId = users[a].userIM;
                        var name = users[a].userName;

                        //if (avatar1 == "") {
                            var color = avatar_getColor(qyxBindId);
                            img_url = "<div class='user_pic_div' style='background-color: " + color + "'>" + avatar_name(name) + "</div>"
                        //} else {
                        if (avatar1.length > 0) {
                            var src = avatar_getUrl(localStorage.user_id, localStorage.token, avatar1);
                            console.log("avatarurl---",src);
                            console.log("userName---",users[i].userName);
                            img_url += "<img src='" + src + "' class='user_pic' hidden>";
                        }

                        html_users += "<div class='user_mid' id='" + users[a].userId + "' qyxBindId='" + qyxBindId + "' name='" + users[a].userName + "' avatar='" + users[a].avatar + "' is_choice='" + _choice + "'>" +
                            ""+_img+"" +
                            "<div class='user_left'>" +
                            "" + img_url + "" +
                            "<div class='user_name'>" + users[a].userName + "</div>" +
                            "</div>" +
                            "</div>";
                    }

                    $(".team_content_bigest").append(html).append(html_users);

                    showAvatar(".user_pic");
                }
                else {
                    if (data.statusCode == 202 || data.statusCode == 203){
                        $(".token_iframe").show();
                    }
                    else {
                        $(".addMemberProject-alert").text(data.message).show().fadeOut(2000);
                    }
                }
            },
            error:function(){
                $(".addMemberProject-alert").text("网络不给力").show().fadeOut(2000);
            }
        });
    }

    //点击行获取部门下的成员列表
    var _team;
    $(document).on('click','.team_mid',function(){
        $(this).css("borderBottom","1px solid #e5e5e5");
        _team = $(this).parent();
        var is_choice = $(this).attr("is_choice");
        if(is_choice=="0"){
            var deptId = $(_team).attr("id");
            var url    = tk_apiurl+"contacteam/mydeptsall";
            var data   = {"userId":user_id,"token":token,"data":JSON.stringify({'teamId':group_id,'deptId':deptId})};
            $.ajax({
                beforeSend:function(){
                    $(".addMemberChange-p").text("正在获取部门人员");
                    $(".addMemberChange-alert").show();
                },
                complete: function () {
                    $(".addMemberChange-alert").hide();
                },
                async: true,
                crossDomain: true,
                url: url,
                method: "POST",
                data:data,
                jsonpCallback:"jsoncallback",
                dataType: "jsonp",
                success:function(d){
                    var data='';
                    var data1='';
                    data = eval('('+d+')');
                    if (data.statusCode == 200){
                        data1 = eval('('+data.result+')');
                        var users = data1.users;

                        var html="";

                        for(var i=0;i<users.length;i++){
                            var _choice = "0";
                            var _img    = "<img src='../../images/task/circleCheckBoxUnselect.png' class='tick_icon'>";

                            for(var j=0;j<contact_arr.length;j++){
                                if(contact_arr[j]==users[i].userId){
                                    _choice = "1";
                                    _img    = "<img src='../../images/task/circleCheckBoxSelect.png' class='tick_icon'>";
                                }
                            }
                            var img_url;
                            var avatar1 = users[i].avatar;
                            var qyxBindId = users[i].userIM;
                            var name = users[i].userName;
                            //if(avatar1==""){
                                var color = avatar_getColor(qyxBindId);
                                img_url = "<div class='user_pic_div' style='background-color: "+color+"'>"+avatar_name(name)+"</div>"
                            //}else{
                            if (avatar1.length > 0) {
                                var src = avatar_getUrl(localStorage.user_id,localStorage.token,avatar1);
                                console.log("avatarurl---",src);
                                console.log("userName---",users[i].userName);
                                img_url += "<img src='"+src+"' class='user_pic' hidden>";
                            }
                            html +="<div class='user_mid' id='"+users[i].userId+"' qyxBindId='"+qyxBindId+"' name='"+name+"' avatar='"+avatar1+"' is_choice='"+_choice+"'>" +
                                ""+_img+"" +
                                "<div class='user_left'>" +
                                ""+img_url+"" +
                                "<div class='user_name'>"+users[i].userName+"</div>" +
                                "</div>" +
                                "</div>";
                        }
                        $(_team).append(html);

                        $(".user_mid").last().css("border","none");
                        showAvatar(".user_pic");
                    }
                    else {
                        if (data.statusCode == 202 || data.statusCode == 203){
                            $(".token_iframe").show();
                        }
                        else {
                            $(".addMemberProject-alert").text(data.message).show().fadeOut(2000);
                        }
                    }
                },
                error:function(d){
                    $(".addMemberProject-alert").text("网络不给力").show().fadeOut(2000);
                }
            });
            $(this).find("img").css("transform","rotate(90deg)");
            $(this).attr("is_choice","1");
        }else{
            $(this).find("img").css("transform","rotate(0deg)");
            $(this).nextAll().hide();
            $(this).attr("is_choice","0");
        }
    });

    //选择联系人
    $(document).on('click','.user_mid',function(){
        var id        = $(this).attr('id');
        var name      = $(this).attr('name');
        var avatar    = $(this).attr('avatar');
        var is_choice = $(this).attr("is_choice");
        var qyxBindId = $(this).attr("qyxBindId");

        if(is_choice=="0"){
            $($(this).children(0)).attr('src','../../images/task/circleCheckBoxSelect.png');
            $(this).attr("is_choice","1");
            contact_arr.push(id);
            contact_name_arr.push(name);
            contact_avatar_arr.push(avatar);
            contact_qyxBindId_arr.push(qyxBindId);
        }else{
            if (id == user_id) {
                $(".addMemberProject-alert").text("不能删除自己").show().fadeOut(2000);
            }else {
                $($(this).children(0)).attr('src','../../images/task/circleCheckBoxUnselect.png');
                $(this).attr("is_choice", "0");
                for (key in contact_arr) {
                    if (contact_arr[key] == id) {
                        contact_arr.splice(key, 1);
                        contact_name_arr.splice(key, 1);
                        contact_avatar_arr.splice(key, 1);
                        contact_qyxBindId_arr.splice(key,1);
                    }
                }
            }
        }

        $('.user_mid').each(function(){
            $(this).children(0).attr('src','../../images/task/circleCheckBoxUnselect.png');
            $(this).attr("is_choice", "0");
            var memberId = $(this).attr('id');
            for (var j=0;j<contact_arr.length;j++){
                if (memberId == contact_arr[j]){
                    $(this).children(0).attr('src','../../images/task/circleCheckBoxSelect.png');
                    $(this).attr("is_choice", "1");
                    break;
                }
            }
        });
    });

    function showAvatar(classname){
        $(classname).one("load",function(){
            $(this).show();
            $(this).prev().hide();
        });
    }

})(jQuery);